//引入数据库错题模块
const ErrorsModel_DB = require("../models/ErrorsModel_DB")
//引入发送前端工具
const Response = require("../utils/ResponseEntity")

class ErrorsController {
    //获取所有类型
    async findAll(req, res, next) {
        try {
            const data = await ErrorsModel_DB.find()
            if (data.length) res.send(Response.success({ msg: "查询成功", data }))
            else res.send(Response.error({ msg: "查询失败" }))
        } catch (error) {
            console.log(error);
            res.send(Response.error({ msg: "服务器错误" }))
        }
    }

    //根据学生id查找所有
    async findByStuId(req, res, next) {
        try {
            const { id } = req.query
            if (id) {
                const data = await ErrorsModel_DB.find({ studentId: id }).populate("exerciseId")
                if (data.length) {
                    res.send(Response.success({ data }))
                } else res.send(Response.error({ msg: "查询失败" }))
            } else res.send(Response.error({ msg: "学生id为空" }))
        } catch (error) {
            console.log(error);
            res.send(Response.error({ msg: "服务器错误" }))
        }
    }

    //根据错题id删除
    async deleteById(req, res, next) {
        try {
            const { id } = req.query
            if (id) {
                const data = await ErrorsModel_DB.deleteOne({ _id: id })
                if (data.deletedCount == 1) {
                    res.send(Response.success({ msg: "删除成功" }))
                } else res.send(Response.error({ msg: "删除失败" }))
            } else res.send(Response.error({ msg: "错题id为空" }))
        } catch (error) {
            console.log(error);
            res.send(Response.error({ msg: "服务器错误" }))
        }
    }

    //删除错题
    deleteByArray(req, res, next) {
        try {
            //接收数组
            let { arr } = req.body
            arr = JSON.parse(arr)
            if (arr.length) {
                arr.forEach(async (item) => {
                    const data = await ErrorsModel_DB.deleteOne({ _id: item })
                });
            }
            res.send(Response.success({ msg: "删除成功" }))
        } catch (error) {
            console.log(error);
            res.send(Response.error({ msg: "服务器错误" }))
        }
    }
}

const errors = new ErrorsController()
module.exports = errors